<?php

namespace app\common\storage;

use app\admin\model\StorageChunks;
use app\admin\model\StoragePath;
use think\facade\Log;

class ReaderStorage extends CommonStorage
{

    protected $modelPath = null;

    public function __construct(StoragePath $model_path)
    {
        $this->modelPath = $model_path;

        $this->getFlysystem();
    }

    protected function waitFileCompletion()
    {

        $file_path = $this->buildFileTempPath($this->modelPath->chunk_list_md5);

        $filesize = filesize($file_path);
        if ($filesize < $this->modelPath->size) {
            sleep(3);

            $this->waitFileCompletion($file_path);
        }
    }

    public function stream()
    {
        Log::debug('开始读取数据');
        $file_temp_path = $this->buildFileTempPath($this->modelPath->chunk_list_md5);

        Log::debug('本地缓存：' . $file_temp_path);

        if (file_exists($file_temp_path)) {
            Log::debug('缓存已存在');
            if (empty($this->modelPath->mime_type)) {
                $content_type = mime_content_type($file_temp_path);

                $this->modelPath->content_type = $content_type;
            }

            $this->waitFileCompletion();

            return fopen($file_temp_path, 'rb');
        }

        Log::debug('缓存不存在，从存储位置读取并缓存');

        // 文件需要的空间
        $this->clearFileTemp($this->modelPath->size);

        $handle = fopen($file_temp_path, 'wb+');

        $list_chunks = StorageChunks::where('storage_path_id', $this->modelPath->id)
            ->order('sort', 'asc')
            ->select();

        foreach ($list_chunks as  $model_chunks) {
            $chunk_content = $this->readChunk($model_chunks->chunk_md5);

            $chunk_size = strlen($chunk_content);

            fwrite($handle, $chunk_content, $chunk_size);
        }

        fclose($handle);

        if (empty($this->modelPath->mime_type)) {
            $content_type = mime_content_type($file_temp_path);

            $this->modelPath->content_type = $content_type;
        }

        return fopen($file_temp_path, 'rb');
    }

    public function string()
    {
        $file_rescource = $this->stream();

        $contents = '';
        while (!feof($file_rescource)) {
            $contents .= fread($file_rescource, 8192);
        }
        fclose($file_rescource);

        return $contents;
    }
}
